<template>
  <el-dialog :visible="visible" :title="formTitle" width="40%" :before-close="close">
    <el-form :model="localQueryConfig" :rules="rules" ref="form">
      <el-form-item label="名称" prop="queryName">
        <el-input v-model="localQueryConfig.queryName"></el-input>
      </el-form-item>
      <el-form-item label="查询sql" prop="querySql">
        <el-input v-model="localQueryConfig.querySql"></el-input>
      </el-form-item>
      <el-form-item label="关联数据库配置" prop="dbConnectionId">
        <el-select v-model="localQueryConfig.dbConnectionId" clearable placeholder="请选择 数据库连接" style="width: 300px;">
          <el-option
              v-for="item in selectConnectionList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>

import {getDbConnectionConfigs} from "@/services/apiService";

export default {
  props: {
    queryConfig: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean
    }
  },
  data() {
    return {
      selectConnectionList: [],
      localQueryConfig: { ...this.queryConfig },
      rules: {
        queryName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        querySql: [{ required: true, message: '查询不能为空', trigger: 'blur' }],
      }
    };
  },
  watch: {
    queryConfig: {
      deep: true,
      handler(newVal) {
        this.localQueryConfig = { ...newVal };
      }
    }
  },
  computed: {
    formTitle() {
      return this.localQueryConfig.id ? '编辑 query 配置' : '新增 query 配置';
    }
  },
  mounted() {
    this.loadSelectConnectionValue();
  },
  methods: {
    async loadSelectConnectionValue(){
      const response = await getDbConnectionConfigs();
          // axios.get('http://localhost:9999/v1/module/dbConnectionConfig/list');
      if (response.data.success) {
        this.selectConnectionList = response.data.data.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
      } else {
        this.$message.error(response.data.message || '获取数据失败');
      }
    },
    close() {
      this.localQueryConfig = {};
      this.$refs.form.clearValidate();
      this.$emit('close');
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('save', {...this.localQueryConfig});
        }
      });
    }
  }
};
</script>